package com.itwenke.springbootdemo.shiroini;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

public class Demo {

    @Test
    public void authen() {
        // 创建 SimpleAccountRealm
        IniRealm iniRealm = new IniRealm("classpath:shiro.ini");

        // 创建 DefaultSecurityManager
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        // DefaultSecurityManager 与 IniRealm 建立连接
        securityManager.setRealm(iniRealm);

        // Subject 和 DefaultSecurityManager 建立关系
        SecurityUtils.setSecurityManager(securityManager);

        // 获取 Subject
        Subject subject = SecurityUtils.getSubject();

        // 发起认证
        subject.login(new UsernamePasswordToken("admin", "admin"));
        System.out.println("是否认证通过：" + subject.isAuthenticated());

        // 角色校验
        System.out.println("是否拥有超级管理员角色：" + subject.hasRole("超级管理员"));

        // 权限校验
        System.out.println("是否拥有添加用户权限：" + subject.isPermitted("user:add"));
        subject.checkPermission("user:update"); // 没有权限就抛异常：org.apache.shiro.authz.UnauthorizedException
    }
}
